package com.heima.user.interceptor;

import com.alibaba.fastjson.JSON;
import com.heima.model.app.entity.ApUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;

import com.heima.utils.common.AppThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AppTokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId) && !StringUtils.equals("0", userId)) {
            ApUser user=new ApUser();
            user.setId(Long.parseLong(userId));
            AppThreadLocalUtil.setUser(user);
            return super.preHandle(request, response, handler);
        }
        //没有权限
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(responseResult));

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        AppThreadLocalUtil.clear();
        super.postHandle(request, response, handler, modelAndView);
    }
}
